import type { Router } from 'vue-router';
import NProgress from 'nprogress'; // progress bar
import { useUserStore } from '@/store';
import { getToken } from '@/utils/auth';

export default function setupUserLoginInfoGuard(router: Router) {
  router.beforeEach(async (to, _from, next) => {
    NProgress.start();
    const userStore = useUserStore();

    // 检查是否访问登录页面
    if (to.path === '/login') {
      // 如果已经登录，重定向到首页
      if (getToken() && userStore.role) {
        next({ name: 'Workplace' });
        return;
      }
      next();
      return;
    }

    // 检查是否有token
    const token = getToken();
    if (!token) {
      // 没有token，重定向到登录页面
      next({ path: '/login', query: { redirect: to.fullPath } });
      return;
    }
    next();
  });
}
